package com.Adapters.Items;


import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.Animations.AnimUtil;
import com.Animations.AnimUtil.AnimationCompleted;
import com.Animations.AnimationLists;
import com.Data.Post;
import com.Data.Post.onDeletePictureCompleted;
import com.Data.User;
import com.Dialogs.DialogText;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Listeners.PostItemsListeners.CommentClickListener;
import com.Listeners.PostItemsListeners.LikeClickListener;
import com.Listeners.PostItemsListeners.LikeCompleted;
import com.Listeners.PostItemsListeners.LocationClickListener;
import com.Listeners.PostItemsListeners.ProfileClickListener;
import com.Listeners.PostItemsListeners.TagClickListener;
import com.Managers.DirManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.UserManagerClass;
import com.TextFormat.UtilFonts;
import com.UtilDate.UtilDate;
import com.activities.ActivityProfile;
import com.activities.DefaultFunctions;
import com.shareup.R;


public class ItemPostText implements ItemPost {

    private boolean animate = true;

    private Context context;

    private ViewHolder holder;

    private final LayoutInflater inflater;

    private final User Logged;

    private DefaultFunctions main;

    private final Post picture;

    class DialogClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {

            {
                createDialogPicture();
            }
        }
    }

    class ViewHolder {

        public ImageView action;

        public TextView comment;

        public ImageView comment_button;

        public TextView comments_count;

        public RelativeLayout container;

        public TextView date;

        public ToggleButton like_button;

        public TextView likes_count;

        public ImageView location_button;

        public TextView name;

        public ImageView profile;

        public ImageView tag_button;

        public TextView tags_count;

    }

    public ItemPostText(LayoutInflater inflater, Post picture,
                DefaultFunctions main) {

        super();

        this.inflater = inflater;
        this.picture = picture;
        this.context = main.getParentActivity();
        this.main = main;
        this.Logged = UserManagerClass.UserLogged;

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#AnimateIn()
     */
    @Override
    public void AnimateIn() {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#AnimateOut(com.Animations.AnimUtil.
     * AnimationCompleted)
     */
    @Override
    public void AnimateOut(AnimationCompleted callback) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#clearAnimatonList()
     */
    @Override
    public void clearAnimatonList() {

        AnimationLists.displayedText.clear();

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#delete()
     */
    @Override
    public void delete() {

        AlertDialog.Builder dg = new AlertDialog.Builder(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_actions, null);
        TextView message = (TextView) v.findViewById(R.id.message_dialog);
        UtilFonts.setTextRegularFont(message);
        Button accept = (Button) v.findViewById(R.id.dialog_action_a_button);
        UtilFonts.setTextRegularFont(accept);
        Button cancel = (Button) v.findViewById(R.id.dialog_action_c_button);
        UtilFonts.setTextRegularFont(cancel);
        //
        message.setText(R.string.dialog_question_delete_picture_message);
        //
        dg.setView(v);
        //
        final AlertDialog alert = dg.create();
        accept.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                removeAt();

                alert.cancel();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                alert.cancel();
            }
        });
        //
        //
        //
        alert.show();

    }

    // /////////////////////////////////////////////////
    // CLASS TO SHOW PROFILE FRIEND INFO
    // ///////////////////////////////////////////////

    // /////////////////////////////////////////////////
    // CLASS TO SHOW LOCATION INFO
    // ///////////////////////////////////////////////

    // /////////////////////////////////////////////////
    // SET THE OWNERSHIP TO SET OR DELETE PICTURE
    // ///////////////////////////////////////////////

    @Override
    public int getCommentsCount() {

        return picture.getPictureCounters().getCommentsCount();
    }

    // /////////////////////////////////////////////////
    // CLASS TO SHOW PICTURE IN GALLERY
    // ///////////////////////////////////////////////

    @Override
    public int getLikesCount() {

        return picture.getPictureCounters().getLikesCount();
    }

    @Override
    public int getPostId() {

        return picture.getID();
    }

    @Override
    public String getPublicationDate() {

        return picture.getPublicationDate();
    }

    // /////////////////////////////////////////////////
    // CLASS TO HANDLE COMMENT CLICK
    // ///////////////////////////////////////////////

    @Override
    public View getView(View convertView, int position) {

        View view = null;

        if (convertView == null) {

            ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.item_post_text, null);
            holder = new ViewHolder();
            setTextsLayout(viewGroup);
            viewGroup.setTag(holder);
            view = viewGroup;

        }
        else {
            holder = (ViewHolder) convertView.getTag();
            view = convertView;
        }

        boolean firstDisplay = !AnimationLists.displayedText.contains(picture.getID());
        if (firstDisplay) {
            AnimUtil.PostIn(context, holder.container);
            AnimationLists.displayedText.add(picture.getID());
        }
        else
            AnimUtil.animateFadeIn(holder.container);

        setTexts();

        return view;
    }

    @Override
    public int getViewType() {

        return RowType.TEXT_POST.ordinal();
    }

    public boolean isAnimate() {

        return animate;
    }

    public void setAnimate(boolean animate) {

        this.animate = animate;
    }

    @Override
    public void setCommentsCount(int count) {

        picture.getPictureCounters().setCommentsCount(count);

    }

    public void setCurrentAsProfile() {

        Uri picname = DirManagerClass.getPathFromPicture(picture.getPathFull());

        Intent intent = new Intent(context, ActivityProfile.class);
        intent.putExtra("uri", picname.toString());

        main.getParentActivity().startActivity(intent);
        AnimUtil.getActivityTransition(main.getParentActivity(), true);
    }

    @Override
    public void setLikesCount(int count) {

        picture.getPictureCounters().setLikesCount(count);

    }

    @Override
    public void updatePublicationDate(String newDate) {

        picture.setPublicationDate(newDate);

    }

    private void createDialogPicture() {

        DialogText dl = new DialogText(context, true);
        dl.ItemText = this;
        dl.setTitle(Logged.getRealName());
        dl.show();
    }

    private void downloadImageProfile() {

        if (Logged.getID() == picture.getUser().getID()) {

            holder.profile.setImageDrawable(FragmentManagerClass.aMenu.getProfile().getDrawable());

        }
        else {

            ProfilePictureDownloader pd = new ProfilePictureDownloader();
            pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

                @Override
                public void completed(Bitmap result) {

                    holder.profile.setImageBitmap(result);

                }
            });
            pd.execute(picture.getUser().getProfilePicture());
        }

    }

    private String getTagsCount() {

        String tres = picture.getTags().trim();
        if (!tres.equals("")) {
            String[] tresp = tres.split(",");
            int total = tresp.length;
            if (tres.length() > 0 && tres.charAt(0) == ',')
                total--;
            tres = "" + total;
        }
        else {
            tres = "0";
        }
        //
        return tres;
    }

    private void removeAt() {

        Post pic = new Post(Post.ACTION_DELETE, context, null);
        pic.setID(picture.getID());
        pic.setUser(new User());
        pic.getUser().setID(Logged.getID());
        pic.setCallbackDeletePicture(new onDeletePictureCompleted() {

            @Override
            public void Completed(String result) {

                // WHEN THE DELETE ANIMATION IS COMPLETED THE ITEM IS GOING TO
                // BE DELETED
                AnimUtil.PostOut(context, holder.container, new AnimationCompleted() {

                    @Override
                    public void Completed() {

                        main.remove(picture);
                        holder.container.setVisibility(View.VISIBLE);

                    }
                });

            }
        });
        pic.execute();

    }

    private void setCounters() {

        String cres = ""
                    + picture.getPictureCounters().getCommentsCount();
        String lres = ""
                    + picture.getPictureCounters().getLikesCount();
        //
        holder.likes_count.setText(lres);
        holder.comments_count.setText(cres);
        holder.tags_count.setText(getTagsCount());
        //
        setOwnerShip();
        // START IMAGE DOWNLOAD AFTER ITS SETTLED UP
        downloadImageProfile();

    }

    private void setImagesLayout(View itemView) {

        holder.profile = (ImageView) itemView.findViewById(R.id.user_image_profile);
        //
        holder.action = (ImageView) itemView.findViewById(R.id.post_button_action);
        //
        holder.comment_button = (ImageView) itemView.findViewById(R.id.post_button_comment);
        //
        holder.like_button = (ToggleButton) itemView.findViewById(R.id.post_button_like);
        //
        holder.tag_button = (ImageView) itemView.findViewById(R.id.post_button_tag);
        //
        holder.location_button = (ImageView) itemView.findViewById(R.id.post_button_location);

    }

    private void setOwnerShip() {

        int idOwner = picture.getUser().getID();
        int idLogger = Logged.getID();

        if (idOwner != idLogger) {
            holder.action.setVisibility(View.GONE);
        }
        else {
            if (holder.action.getVisibility() == View.GONE) {
                holder.action.setVisibility(View.VISIBLE);
            }
        }

    }

    private void setTexts() {

        holder.action.setOnClickListener(new DialogClickListener());

        // SETS THE DIFFERENCE OF TIME
        setTimeDiff();

        holder.like_button.setOnClickListener(new LikeClickListener(picture, new LikeCompleted() {

            @Override
            public void Completed() {

                setCounters();

            }
        }));
        //
        holder.comment_button.setOnClickListener(new CommentClickListener(picture));
        holder.tag_button.setOnClickListener(new TagClickListener(picture));

        //
        if (picture.getGeoTag().getLatitude() != 0
                    && picture.getGeoTag().getLongitude() != 0) {
            holder.location_button.setVisibility(View.VISIBLE);
            holder.location_button.setOnClickListener(new LocationClickListener(picture, RowType.TEXT_POST));
        }
        else {
            holder.location_button.setVisibility(View.GONE);
        }
        //
        holder.like_button.setChecked(false);
        //
        if (picture.getPictureCounters() != null
                    && picture.getPictureCounters().getIsMine() > 0) {
            holder.like_button.setChecked(true);
        }

        holder.comment.setText(picture.getComment());
        holder.name.setText(picture.getUser().getRealName());
        holder.name.setOnClickListener(new ProfileClickListener(picture, main.getParentActivity()));
        holder.profile.setOnClickListener(new ProfileClickListener(picture, main.getParentActivity()));

        setCounters();
    }

    private void setTextsLayout(View itemView) {

        holder.comment = (TextView) itemView.findViewById(R.id.user_comment);
        holder.name = (TextView) itemView.findViewById(R.id.user_name);
        holder.date = (TextView) itemView.findViewById(R.id.user_date);
        //
        holder.likes_count = (TextView) itemView.findViewById(R.id.post_text_likes_count);
        holder.comments_count = (TextView) itemView.findViewById(R.id.post_text_comments_count);
        //
        holder.tags_count = (TextView) itemView.findViewById(R.id.post_tags_counter);
        //
        holder.container = (RelativeLayout) itemView.findViewById(R.id.post_container_all);
        //
        UtilFonts.setTextRegularFont(holder.comment);
        UtilFonts.setTextRegularFont(holder.comments_count);
        UtilFonts.setTextRegularFont(holder.tags_count);
        UtilFonts.setTextRegularFont(holder.likes_count);

        UtilFonts.setTextBoldFont(holder.name);
        UtilFonts.setTextRegularFont(holder.date);
        //
        // CALL TO SET IMAGE VIEWS

        setImagesLayout(itemView);
    }

    private void setTimeDiff() {

        UtilDate dt = new UtilDate(holder.date.getContext());
        dt.setTimeDifference(picture.getPublicationDate(), holder.date);
    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#getPosition()
     */
    @Override
    public int getPosition() {

        // TODO Auto-generated method stub
        return 0;
    }
}
